package com.example.activelifecycletest.service.simple;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.example.activelifecycletest.R;
import com.example.activelifecycletest.constents.MyLog;

/**
 * 服务练习
 * @author zhangding
 * @date 2022年5月11日21:20:29
 */
public class MyService extends Service {
    public MyService() {
    }

    /**
     * 服务创建时候调用
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(MyLog.LOG_ZHANG,"服务创建啦！");
        Intent intent = new Intent(this,SimpleServiceActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
        /*
          begin:需要特殊处理的，不然会报错导致前端服务无法创建
         */
        String id = "channelId";
        String name = "channelName";
        NotificationChannel channel = new NotificationChannel(id,name, NotificationManager.IMPORTANCE_LOW);
        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);
        /*
         end
         */
        Notification notification = new Notification.Builder(this)
                .setChannelId(id)
                .setContentTitle("这是标题")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setContentIntent(pendingIntent)
                .build();
        startForeground(1,notification);
    }

    /**
     * 首次启动时候调用
     * 去写希望立即去执行的动作
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(MyLog.LOG_ZHANG,"服务启动啦！");
        return super.onStartCommand(intent, flags, startId);

    }

    /**
     * 服务销毁时候调用
     * 释放不再使用的资源
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(MyLog.LOG_ZHANG,"服务销毁啦！");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}